#!/bin/bash -e
#   * compile instructions: put this file in
#   *         `steamapps/common/Dyson Sphere Program/CustomMod`
#   * folder, open a terminal in the same folder, and execute:
#   *
#   * ```
#   *     chmod +x ${file}.cs
#   *     ./${file}.cs
#   * ```
#   *
#   * then the mod will be compiled automatically.
#   *
#   * Here we wrote a shebang like file, which is correct
#   * in my computer (Manjaro XFCE), if such script do not work
#   * in your computer, you could just try the instructions below :

if [ -z "$__DOTNET_CSC" ]; then
    export __DOTNET_CSC="`find /usr/share/dotnet -type f -name dotnet` `find /usr/share/dotnet -name csc.dll`"
    echo '$'"__DOTNET_CSC not set yet, you should execute"
    echo "export __DOTNET_CSC='$__DOTNET_CSC'"
    echo "manually, or this alert will occur each time you execute this script."
fi

__MODE_VERBOSE=83 # is the line number of "#define VERBOSE", may be modified
__MODE_DEBUG__=$((__MODE_VERBOSE+1))
__MODE_RELEASE=$((__MODE_DEBUG__+1))

case $1 in
    V)       _MODE__SELECT_=$__MODE_VERBOSE     ;;
    v)       _MODE__SELECT_=$__MODE_VERBOSE     ;;
    VERBOSE) _MODE__SELECT_=$__MODE_VERBOSE     ;;
    verbose) _MODE__SELECT_=$__MODE_VERBOSE     ;;
    D)       _MODE__SELECT_=$__MODE_DEBUG__     ;;
    d)       _MODE__SELECT_=$__MODE_DEBUG__     ;;
    DEBUG)   _MODE__SELECT_=$__MODE_DEBUG__     ;;
    debug)   _MODE__SELECT_=$__MODE_DEBUG__     ;;
    *)       _MODE__SELECT_=$__MODE_RELEASE     ;;
esac

# export GAME_NAME="${0%\.cs}" # now, file name should be equals to ${GAME_NAME}.cs, the benefit is, we could only change the name, rather than change filename and $GAME_NAME.
# export GAME_NAME="$(basename `pwd`)" # now, file name should be equals to ${GAME_NAME}.cs, the benefit is, we could only change the name, rather than change filename and $GAME_NAME.
export GAME_NAME="wtl"
export FILE_NAME="$0"
export GAME_DIR="$GAME_NAME"                                # might be modified
export ASSEMBLY="Assembly-CSharp"                           # might be modified
export PLUGIN_ID="Neutron3529.Cheat"                        # should be modified
export NAMESPACE_ID="Neutron3529.Cheat"                     # should be modified
export GAME_BASE_DIR="common/$GAME_DIR"

( yes "" | head -n $_MODE__SELECT_ | head -n-1  ; tail $FILE_NAME -n+$_MODE__SELECT_ ) | sed s/%%NAMESPACE_ID%%/${NAMESPACE_ID}/g | sed s/%%PLUGIN_ID%%/${PLUGIN_ID}/g | $__DOTNET_CSC -nologo -t:library \
  -r:"${GAME_BASE_DIR}/BepInEx/core/BepInEx.dll" \
  -r:"${GAME_BASE_DIR}/BepInEx/core/0Harmony.dll" \
  -r:"${GAME_BASE_DIR}/BepInEx/core/BepInEx.Harmony.dll" \
  `[ -e "${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/netstandard.dll" ] && echo "-r:\"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/netstandard.dll\""` \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/System.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/System.Core.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.CoreModule.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/mscorlib.dll" \
  $(for i in `printf "%q " ${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/$ASSEMBLY*.dll` ; do echo -r:"$i" ; done) \
  -out:"${GAME_BASE_DIR}/BepInEx/plugins/${FILE_NAME%.*}".dll \
  -optimize `[ "$_MODE__SELECT_" == "$__MODE_DEBUG__" ] && echo -debug` \
  - && rm -f "${GAME_BASE_DIR}/BepInEx/config/${PLUGIN_ID}.cfg";

if [ -n "$2" ]; then
    git add ${FILE_NAME}
    case $2 in
        R) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        r) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        RANDOM) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        random) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        U) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        u) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        UPLOAD) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        upload) git commit -am "`curl -s http://whatthecommit.com/index.txt`" ;;
        *) git commit -am "$2" ;;
    esac
    git push
fi
exit


#define VERBOSE // the line of __MODE_VERBOSE
#define DEBUG



using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;

using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

namespace %%NAMESPACE_ID%%
{
    [BepInPlugin("%%PLUGIN_ID%%", "%%NAMESPACE_ID%%", "0.1.0")]
    public class Cheat : BaseUnityPlugin {
#if DEBUG
        public static Action<string> logger;
#else
        public static void logger(string s){}
#endif
        public static float non_digital_factor=-1;
        public static float time_mul=0.1f;
        void Start() {
            var harmony=new Harmony("Neutron3529.wtl");
#if DEBUG
            logger=Logger.LogInfo;
#endif
            logger("这是玩wtl都开修改器的屑");

            if((time_mul=Config.Bind("config", "time_mul", time_mul, "训练器处理时间乘数").Value)<1f){
                if(time_mul>0f){
                    harmony.PatchAll(typeof(LogicGetWorkTimeByKeyName));
                    logger("time_mul patched");
                }
            }
            if(Config.Bind("config", "min_error_is_0", false, "训练器错误率可以为0").Value){ // 有bug？
                harmony.PatchAll(typeof(CharacterTraitDataGetTraitEffect));
                logger("min_error_is_0 patched");
            }
        }
        class CharacterTraitDataGetTraitEffect {
            static IEnumerable<MethodBase> TargetMethods()
            {
                foreach(Type t in new Type[]{
                    typeof(BaseBlock),
                    typeof(ARMA),
                    typeof(GeneticCopyBlockColor),
                    typeof(PerceptronColor),
                    typeof(PerceptronShape),
                    typeof(RNNCELL),
                    typeof(Rosenblat)
                }){
#if DEBUG
                    logger("注入"+t.ToString()+"的Init方法+1");
#endif
                    yield return t.GetMethod("Init");
                }
            }
            static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) {
                //return instructions;
                return new CodeMatcher(instructions)
                    .MatchForward(false, // false = move at the start of the match, true = move at the end of the match
                        new CodeMatch(i=> i.opcode==OpCodes.Stfld && ((FieldInfo)i.operand).Name == "minError" ) // match method 2
                    ).Repeat( matcher => // Do the following for each match
                        matcher
                        .InsertAndAdvance(
                            new CodeInstruction(OpCodes.Pop,null)
                            new CodeInstruction(OpCodes.Ldc_R4,0f)
                         ).Advance(1)
                    ).InstructionEnumeration();
            }
        }
        [HarmonyPatch(typeof(Logic), "GetWorkTimeByKeyName")]
        class LogicGetWorkTimeByKeyName {
            static float Postfix(float __result) {
                return __result*time_mul;
            }
        }
    }
}

